<?php
/**
 * This file is form http://findcat.cn
 *
 * @link     https://findcat.cn
 * @email    1476982312@qq.com
 */
namespace App\Exceptions;

use Exception;
use Illuminate\Support\MessageBag;

/**
 * Class ResourceException.
 */
class ResourceException extends HttpException implements MessageBagErrors
{
    /**
     * MessageBag errors.
     *
     * @var \Illuminate\Support\MessageBag
     */
    protected $errors;

    /**
     * Create a new resource exception instance.
     *
     * @param string                               $message
     * @param array|\Illuminate\Support\MessageBag $errors
     * @param \Exception                           $previous
     * @param array                                $headers
     * @param int                                  $code
     */
    public function __construct(
        $message = null,
        $errors = null,
        Exception $previous = null,
        $headers = [],
        $code = 0
    ) {
        if (is_null($errors)) {
            $this->errors = new MessageBag();
        } else {
            if (is_array($errors)) {
                $message      = current($errors);
                $this->errors = new MessageBag($errors);
            } else {
                $message      = $errors;
                $this->errors = $errors;
            }
        }
        parent::__construct(422, $message, $code, null, $previous, $headers);
    }

    /**
     * Get the errors message bag.
     *
     * @return \Illuminate\Support\MessageBag
     */
    public function getErrors()
    {
        return $this->errors;
    }

    /**
     * Determine if message bag has any errors.
     *
     * @return bool
     */
    public function hasErrors()
    {
        return !$this->errors->isEmpty();
    }
}
